package com.example.demo2;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class EncryptionDataDecorator extends DataLoaderDecorator {

    public EncryptionDataDecorator(DataLoader dataLoader) {
        super(dataLoader);
    }

    @Override
    public String read() {
        String info = super.read();
        String read = read(info);
        return read;
    }

    @Override
    public void write(String data) {
        super.write(encode(data));
    }

    private String read(String data) {
        String info = null;
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            info = new String(decoder.decode(data.getBytes()), "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return info;
    }


    private String encode(String data) {
        Base64.Encoder encoder = Base64.getEncoder();
        String toString = null;
        try {
            toString = encoder.encodeToString(data.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return toString;
    }

}
